import { FastifyInstance } from "fastify";
import { Static, Type } from "@sinclair/typebox";
import { Event } from "@db";

const eventJoinParams = Type.Object({
    eventId: Type.Number(),
});

export const join = async (fastify: FastifyInstance) => {
    fastify.post<{ Params: Static<typeof eventJoinParams> }>(
        "/student/event/join/:eventId",
        {
            preHandler: fastify.auth("student"),
            schema: {
                tags: ["student"],
                params: eventJoinParams,
            },
        },
        async (req, res) => {
            const event = await Event.findOne({
                where: {
                    id: req.params.eventId,
                },
            });
            console.log(event.dataValues.members);

            if (
                event.dataValues.members.find(
                    (member) => member === req.student.id
                )
            )
                return res.status(409).send({
                    code: "USER_ALREADY_JOINED",
                    message: "Вы уже участвуете",
                });

            event.dataValues.members.push(req.student.id);
            console.log(event.dataValues.members);
            const eventRes = await event.update({
                members: event.dataValues.members,
            });

            console.log(eventRes);

            req.student.update({
                score: req.student.score + 15,
            });

            return res.send({
                message: "Вы присоединились",
            });
        }
    );
};
